package controller;

import model.ChessboardModel;
import model.QueenModel;
import view.QueenView;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.ImageIcon; 

/**
 * Controlador de las casillas del tablero
 * @author Samuel Chávez, Axel Mayorga
 */
public class QueenController implements MouseListener
{
    final String IMAGE_QUEEN = "/resources/queen.jpg";
    QueenView view;
    QueenModel model;
    ChessboardModel chessboard;
    
    public QueenController(QueenView view, QueenModel model, ChessboardModel chessboard)
    {
        this.view = view;
        this.model = model;
        this.chessboard = chessboard;
        
        this.view.addMouseListener(this);
    }

    /**
     * Administrador de la acción del mouse al momento de hacer click en la casilla
     * @param e Evento del mouse
     */
    @Override
    public void mouseReleased(MouseEvent e) {
        if(model.isExistQueen())
        {
            this.view.cleanImage();
            model.setExistQueen(false);
            chessboard.removeQueen(model.getNumber());
        }
        else
        {
            //Verifica que no sean más reinas de las que se especifico
            if(chessboard.getQueens().size() < chessboard.getkQueen())
            {
                String sQuery = UtilityManager.getQueryCheckFail(chessboard, model.getNumber());
                chessboard.addInstructionAt(sQuery);

                //Existen errores anteriores?
                if(this.chessboard.isFail())
                {
                    this.chessboard.setFail(false);
                    UtilityManager.clearFails(this.chessboard.getQueenControllers());
                }
                
                Brain b = new Brain();
                ArrayList<String> fails = UtilityManager.findFail(b.query(sQuery));
                if(fails.isEmpty() || (!fails.isEmpty() && fails.get(0).equals("false")))
                {
                    this.view.setImage(IMAGE_QUEEN);
                    model.setExistQueen(true);
                    chessboard.addQueenAt(model.getNumber());
                }
                else
                {
                    this.chessboard.setFail(true);
                    UtilityManager.failHandler(fails, this, this.chessboard);
                }
            }
        }
    }
    
    @Override
    public void mouseClicked(MouseEvent e) {
        
    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }
    
}
